package client.chat;

import client.service.CustomChannelHandler;
import client.service.TestClient;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * netty Cent
 */

public class ChatClient {

    public static void main(String[] args) {
        ChatClient chatClient = new ChatClient();
        chatClient.connectServer("localhost",8280);
    }


    public void connectServer(String host,int port){

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            //配置Channel
            b.group(group).channel(NioSocketChannel.class)
                    //设置通道选项  有数据立即发送
//                   .option(ChannelOption.TCP_NODELAY,true)
                    .handler(new ChatClientChannelInitializer());

            //获取控制台输入流
            Channel channel = b.connect(host, port).sync().channel();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            while(true){
                String s = bufferedReader.readLine();
                if("exit".equals(s)){
                    channel.close();
                    break;
                }
                //发送    分隔符让服务端正确读取数据
                channel.writeAndFlush( s+"\r\n");
            }
            System.out.println("准备关闭客户端----");
            //等待客户端链接关闭 -- 线程在此处阻塞
        }catch(Exception e){
            e.printStackTrace();
            System.out.println("客户端启动出现异常!");
        }finally{
            //关闭线程释放资源
            group.shutdownGracefully();
            System.out.println("客户端已关闭!");
        }

    }
}
